package cn.smbms.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;

import cn.smbms.pojo.User;
import cn.smbms.service.user.UserService;
import cn.smbms.tools.Constants;

@Controller
public class loginController {
	private Logger logger = Logger.getLogger(loginController.class);
	@Resource
	private UserService userService;
	
	
	@RequestMapping(value="/login.html")
	public String login() {
		logger.debug("以跳转到系统的登录页=================");
		return "login";
	}
	@RequestMapping(value="/dologin.html")
	public String doLogin(@RequestParam String userCode,
						  @RequestParam String userPassword,
						  HttpServletRequest request) throws Exception {
		logger.debug("doLogin()方法实现登录=================");
		User user = userService.login(userCode,userPassword);
		if(null != user){//登录成功
			//放入session
			request.getSession().setAttribute(Constants.USER_SESSION, user);
			//页面跳转（frame.jsp）
			return "redirect:/main.html";
		}else{
			//页面跳转（login.jsp）带出提示信息--转发
			request.setAttribute("error", "用户名或密码不正确");
			return "login";
		}
	}
	
	@RequestMapping(value="/main.html")
	public String main(HttpSession session){
		if (session.getAttribute(Constants.USER_SESSION)==null) {
			return "redirect:/login.html";
		}
		logger.debug("转发重定向到首页frame=================");
		return "frame";
	}
	@RequestMapping(value="exlogin.html",method=RequestMethod.GET)
	public String exLogin(@RequestParam String userCode,
						  @RequestParam String userPassword) throws Exception{
		logger.debug("exLogin==================================");
		//调用service方法,进行用户匹配
		User user =userService.login(userCode, userPassword);
		if (null==user) {//登录失败
			throw new RuntimeException("用户名或者密码不正确!");
		}
		return "redirect:/main.html";
	}
	//注销
	@RequestMapping(value="logout.html")
	public String logout(HttpServletRequest request){
		logger.debug("logout()方法实现注销=================");
		//清除session
		request.getSession().removeAttribute(Constants.USER_SESSION);
		return "login";
	}
}
